﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
using Vkontakte.Api;

namespace VkClientIM.Logic
{
	public class ContactList
	{
		private Dictionary<long,Profile> _dictionary=new Dictionary<long, Profile>();
		private Dictionary<long, string> _friendsLists = new Dictionary<long, string>();
		private ObservableCollection<Profile> _contactList = new ObservableCollection<Profile>();

		private string _lastSearchPattern = "";

		public void AddProfile(Profile profile)
		{
			lock (_dictionary)
			{
				if ( !_dictionary.ContainsKey( profile.UserID ) )
				{
					_dictionary.Add( profile.UserID, profile );
					profile.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(profile_PropertyChanged);
					_contactList.Add( profile );
				}
			}
		}

		void profile_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			
			if (e.PropertyName=="Online")
			{
				int index= _contactList.IndexOf((Profile) sender);
				_contactList.Move(index, index);
			}
		}

		public void LoadGroups(FriendsList[] lists)
		{
			for (int i = 0; i < lists.Length; i++)
			{
				_friendsLists.Add(lists[i].ID, lists[i].Name);
			}
		}

		public Profile GetByUserID(long userID)
		{
			return GetByUserID( userID, false );
		}

		public Profile GetByUserID(long userID,bool create)
		{
			Profile ret = null;
			lock (_dictionary)
			{
				if ( _dictionary.ContainsKey( userID ) )
				{
					ret = _dictionary[ userID ];
				}
				if ( ( ret == null ) && ( create ) )
				{
					ret = new Profile( userID );
					_dictionary.Add( userID, ret );
					if (NeedProfileUpdate!=null)
					{
						NeedProfileUpdate(userID);
					}
				}
			}
			return ret;
		}

		public NotifyCollectionChangedProxy<ObservableCollection<Profile>, Profile> VisibleContactList
		{
			get { return new NotifyCollectionChangedProxy<ObservableCollection<Profile>, Profile>( _contactList ); }
		}

		public event Action<long> NeedProfileUpdate;
	}

}